#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Simple Hook - Quick Crypto Analysis
"""

import frida
import sys
import time

print("\n[1] Connecting to device...")
device = frida.get_usb_device()
print(f"    Connected: {device.name}")

print("[2] Attaching to PID 2586...")
session = device.attach(2586)
print("    Attached!")

print("[3] Loading hook script...")

# Simple hook script
hook_code = """
Java.perform(function() {
    console.log("\\n[HOOK READY]\\n");
    
    // Hook SecretKeySpec to capture AES key
    var SecretKeySpec = Java.use("javax.crypto.spec.SecretKeySpec");
    SecretKeySpec.$init.overload('[B', 'java.lang.String').implementation = function(key, algorithm) {
        console.log("\\n" + "=".repeat(80));
        console.log("[AES KEY FOUND]");
        console.log("Algorithm: " + algorithm);
        console.log("Key Length: " + key.length);
        
        var hexKey = "";
        for (var i = 0; i < key.length; i++) {
            hexKey += ("0" + (key[i] & 0xFF).toString(16)).slice(-2);
        }
        console.log("Key (HEX): " + hexKey);
        
        var strKey = "";
        for (var i = 0; i < key.length; i++) {
            var c = key[i] & 0xFF;
            strKey += (c >= 32 && c <= 126) ? String.fromCharCode(c) : ".";
        }
        console.log("Key (STR): " + strKey);
        console.log("=".repeat(80) + "\\n");
        
        return this.$init(key, algorithm);
    };
    
    // Hook IvParameterSpec to capture IV
    var IvParameterSpec = Java.use("javax.crypto.spec.IvParameterSpec");
    IvParameterSpec.$init.overload('[B').implementation = function(iv) {
        console.log("\\n[IV FOUND]");
        
        var hexIv = "";
        for (var i = 0; i < iv.length; i++) {
            hexIv += ("0" + (iv[i] & 0xFF).toString(16)).slice(-2);
        }
        console.log("IV (HEX): " + hexIv);
        
        var strIv = "";
        for (var i = 0; i < iv.length; i++) {
            var c = iv[i] & 0xFF;
            strIv += (c >= 32 && c <= 126) ? String.fromCharCode(c) : ".";
        }
        console.log("IV (STR): " + strIv + "\\n");
        
        return this.$init(iv);
    };
    
    // Hook Cipher.doFinal
    var Cipher = Java.use("javax.crypto.Cipher");
    Cipher.doFinal.overload('[B').implementation = function(input) {
        console.log("\\n[CIPHER OPERATION]");
        console.log("Algorithm: " + this.getAlgorithm());
        console.log("Input Length: " + input.length);
        
        var hexInput = "";
        var maxLen = Math.min(32, input.length);
        for (var i = 0; i < maxLen; i++) {
            hexInput += ("0" + (input[i] & 0xFF).toString(16)).slice(-2);
        }
        console.log("Input (first 32 bytes HEX): " + hexInput);
        
        var result = this.doFinal(input);
        
        var hexOutput = "";
        maxLen = Math.min(32, result.length);
        for (var i = 0; i < maxLen; i++) {
            hexOutput += ("0" + (result[i] & 0xFF).toString(16)).slice(-2);
        }
        console.log("Output Length: " + result.length);
        console.log("Output (first 32 bytes HEX): " + hexOutput + "\\n");
        
        return result;
    };
    
    // Hook Base64
    var Base64 = Java.use("android.util.Base64");
    Base64.encodeToString.overload('[B', 'int').implementation = function(input, flags) {
        var result = this.encodeToString(input, flags);
        
        console.log("\\n[BASE64 ENCODE]");
        console.log("Input Length: " + input.length);
        
        var hexInput = "";
        var maxLen = Math.min(16, input.length);
        for (var i = 0; i < maxLen; i++) {
            hexInput += ("0" + (input[i] & 0xFF).toString(16)).slice(-2);
        }
        console.log("Input (first 16 bytes HEX): " + hexInput);
        console.log("Output: " + result.substring(0, Math.min(60, result.length)) + "...\\n");
        
        return result;
    };
    
    console.log("[OK] All hooks installed!\\n");
});
"""

script = session.create_script(hook_code)

def on_message(message, data):
    if message['type'] == 'send':
        print(message['payload'])
    elif message['type'] == 'error':
        print(f"\n[ERROR] {message}")

script.on('message', on_message)
script.load()
print("    Loaded!\n")

print("[4] Hooks active. Now call the API from another terminal:")
print("    curl http://120.27.155.222:9999/api/message/send-test")
print("\n[*] Press Ctrl+C to exit\n")

try:
    sys.stdin.read()
except KeyboardInterrupt:
    print("\n\n[+] Exiting...")
    session.detach()
    print("[OK] Done\n")


